//
//  AppDelegate.m
//  FMJY
//
//  Created by 艾玩科技 on 17/3/21.
//  Copyright © 2017年 随心. All rights reserved.


#import "AppDelegate.h"
#import "LogInViewController.h"
#import "BNCoreServices.h"
#import "MainViewController.h"

#define iOS8 [[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 ? 1 : 0


@interface AppDelegate ()<UNUserNotificationCenterDelegate>


@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    [self.window makeKeyAndVisible];
    self.window.backgroundColor  = [UIColor whiteColor];
    
    
    //APNS 注册
    if (iOS8) {
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIRemoteNotificationTypeBadge
                                                                                             |UIRemoteNotificationTypeSound
                                                                                             |UIRemoteNotificationTypeAlert) categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }else
    {
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
    }
#pragma mark -- 设置启动页面时间 --
    [NSThread sleepForTimeInterval:2.0];  //我这里设置的是3秒
    
    //    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"isLogin"] == YES) {
    
    //已登录，再次打开界面
    //        MainViewController *mainVC = [[MainViewController alloc] init];
    //        UINavigationController *nv = [[UINavigationController alloc] initWithRootViewController:mainVC];
    //        self.window.rootViewController = nv;
    //
    
    //   }
    //    else
    //    {
    
    if (GetUserInfo) {
        MainViewController *mainVC = [[MainViewController alloc] init];
        UINavigationController *nv = [[UINavigationController alloc] initWithRootViewController:mainVC];
        self.window.rootViewController = nv;
    }
    else{
        //未登录，手机号登录界面
        LogInViewController *logVC = [[LogInViewController alloc] init];
        UINavigationController *nav=[[UINavigationController alloc] initWithRootViewController:logVC];
        self.window.rootViewController = nav;
    }
    

    //    }
    
    
    
    //手机号登录界面
    //    LogInViewController *logVC = [[LogInViewController alloc] init];
    //    UINavigationController *nav=[[UINavigationController alloc] initWithRootViewController:logVC];
    //    self.window.rootViewController = nav;
    
#pragma mark -- 导航 --
    [BNCoreServices_Instance initServices:BDAPPKey];
    [BNCoreServices_Instance startServicesAsyn:nil fail:nil];
    
#pragma mark  -- 友盟推送 --
    [UMessage startWithAppkey:@"58f82d39f5ade4272c000c68" launchOptions:launchOptions];
    //注册通知
    [UMessage registerForRemoteNotifications];
    
    [UMessage setLogEnabled:YES];
    return YES;
}

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo
{
    [UMessage didReceiveRemoteNotification:userInfo];
}
#pragma mark 点击推送消息调用的方法
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    [UMessage didReceiveRemoteNotification:userInfo];
    
    
    if (userInfo == nil){
        
        
        return;
    }
    
    NSLog(@"%@",userInfo);
    
    NSMutableDictionary *userInfoDic = [[NSMutableDictionary alloc] init];
    
    if ([[userInfo objectForKey:@"text"] isEqualToString:@"您有新订单，请尽快分配救援师"]) {
        
#pragma mark 有新订单之后发送通知（服务商）
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ServiceProviderAssignedOrderNotif" object:nil];
        
    }
    else if ([[userInfo objectForKey:@"text"] isEqualToString:@"您有订单已被取消，请尽快确认"])
    {
        //汽车描述
        [userInfoDic setObject:[userInfo objectForKey:@"custCarDescr"] forKey:@"cancleOredr_cardesc"];
        //汽车车牌号
        [userInfoDic setObject:[userInfo objectForKey:@"custCarPlate"] forKey:@"cancleOredr_cardNum"];
        //订单号
        [userInfoDic setObject:[userInfo objectForKey:@"orderNo"] forKey:@"cancleOredr_orderNo"];
        //救援地点
        [userInfoDic setObject:[userInfo objectForKey:@"addr"] forKey:@"cancleOredr_addr"];
#pragma mark 订单被取消之后发送通知
        [[NSNotificationCenter defaultCenter] postNotificationName:@"cancleOrderNotif" object:nil userInfo:userInfoDic];
    }
    else if ([[userInfo objectForKey:@"text"] isEqualToString:@"您有新的救援订单，请尽快接单"])
    {
        //救援类型
        [userInfoDic setObject:[userInfo objectForKey:@"helpTypeText"] forKey:@"drivergetorder_helpTypeText"];
        //救援订单号
        [userInfoDic setObject:[userInfo objectForKey:@"orderNo"] forKey:@"drivergetorder_orderNo"];
        //救援地点
        [userInfoDic setObject:[userInfo objectForKey:@"addr"] forKey:@"drivergetorder_addr"];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"DriverGetNewOrderNotif" object:nil userInfo:userInfoDic];
        
    }
    
    
    
}
#ifdef __IPHONE_8_0
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    //register to receive notifications
    [application registerForRemoteNotifications];
}

- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void(^)())completionHandler
{
    //handle the actions
    if ([identifier isEqualToString:@"declineAction"]){
        
        
    }
    else if ([identifier isEqualToString:@"answerAction"])
    {
        
    }
}
#endif
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(nonnull NSData *)deviceToken
{
    NSString *deviceTokenStr = [NSString stringWithFormat:@"%@",[[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]                  stringByReplacingOccurrencesOfString: @">" withString: @""]                 stringByReplacingOccurrencesOfString: @" " withString: @""]];
    [[NSUserDefaults standardUserDefaults]setObject:deviceTokenStr forKey:@"deveiceTokenStr"];
    
    
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    
    
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

//app进入
- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    
    NSLog(@"什么时候调用的");
}


@end
